//
//  RegisterTableViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/7/25.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import HXPhotoPicker
import HandyJSON

// 注册
class RegisterTableViewController: BaseTableViewController {
    
    var leftTitleLabel:UILabel!
    @IBOutlet weak var phoneField: UITextField!
    @IBOutlet weak var verificationCodeField: UITextField!
    @IBOutlet weak var passWordField: UITextField!
    @IBOutlet weak var confirmField: UITextField!
    @IBOutlet weak var shopNameField: UITextField!
    @IBOutlet weak var principalField: UITextField! // 负责人
    @IBOutlet weak var shopAddressLabel: UILabel! // 门店地址
    @IBOutlet weak var detailAddressTextView: UITextView!
    @IBOutlet weak var placeHolderLabel: UILabel!
    @IBOutlet weak var shopImage: UIImageView! // 门店照片
    @IBOutlet weak var businessLicenseImage: UIImageView! // 营业执照
    @IBOutlet weak var agreementLabel: UILabel! // 用户协议
    @IBOutlet weak var checkImage: UIImageView!
    @IBOutlet weak var countLabel: UILabel!
    @IBOutlet weak var verificationBtn: UIButton!
    
    lazy var alertView : AlertContentView = {
        let view = AlertContentView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight), type: 1)
        
        view.backClosure = { [weak self] in
            self?.backBarButtonMethon()
        }
        
        UIApplication.shared.keyWindow?.addSubview(view)
        return view
    }()
    
    var areaId = 0
    var cityId = 0
    
    var shopImgUrl = ""
    var businessLicenseImgUrl = ""
    
    var isShopImg = false
    
    lazy var manager:HXPhotoManager = {
        var mager = HXPhotoManager.init(type: HXPhotoManagerSelectedType.photo)
        var configuration = HXPhotoConfiguration.init()
        configuration.movableCropBox = true
        configuration.movableCropBoxEditSize = true
        configuration.singleSelected = true
        configuration.requestImageAfterFinishingSelection = true
        mager?.configuration = configuration
        return mager!
    }()
    
    lazy var effect:EffectView = {
        let view = EffectView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight))
        view.alpha = 0
        UIApplication.shared.keyWindow?.addSubview(view)
        view.hidenClosure = { [weak self]  in
            self?.hidenAddressPicker()
        }
        return view
    }()
    
    lazy var addressPickerView : AddressPickerView = {
        let view = AddressPickerView.init(frame: CGRect.init(x: 0, y: UIScreen.ScreenHeight, width: UIScreen.ScreenWidth, height: 220 + (Utils.isIphoneX() ? 34 : 0)), cityArray: self.cityArray)
        UIApplication.shared.keyWindow?.addSubview(view)
        view.cancelClosure = { [weak self] in
            self?.hidenAddressPicker()
        }
        
        view.backCityName = { [weak self] (cityName,seleAreaID,seleCityID) in
            self?.shopAddressLabel.text = cityName
            self?.areaId = seleAreaID
            self?.cityId = seleCityID
            self?.hidenAddressPicker()
        }
        return view
    }()
    
    
    var cityArray = [ProvinceModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "注册"
        self.checkImage.isHighlighted = true
        
        self.phoneField.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
        self.verificationCodeField.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
        self.passWordField.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
        self.confirmField.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
        self.shopNameField.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
        self.principalField.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
        self.detailAddressTextView.delegate = self
        self.setTextFieldPlaceholderColor(textField: self.phoneField)
        self.setTextFieldPlaceholderColor(textField: self.verificationCodeField)
        self.setTextFieldPlaceholderColor(textField: self.passWordField)
        self.setTextFieldPlaceholderColor(textField: self.confirmField)
        self.setTextFieldPlaceholderColor(textField: self.shopNameField)
        self.setTextFieldPlaceholderColor(textField: self.principalField)
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(agreementTap))
        self.agreementLabel.isUserInteractionEnabled = true
        self.agreementLabel.addGestureRecognizer(tap)
        
        let shopImageTap = UITapGestureRecognizer.init(target: self, action: #selector(imageViewTap(tap:)))
        self.shopImage.isUserInteractionEnabled = true
        self.shopImage.addGestureRecognizer(shopImageTap)
        
        let imageTap = UITapGestureRecognizer.init(target: self, action: #selector(imageViewTap(tap:)))
        self.businessLicenseImage.isUserInteractionEnabled = true
        self.businessLicenseImage.addGestureRecognizer(imageTap)

    }
    
    func setTextFieldPlaceholderColor(textField:UITextField){
        textField.setValue(UIColor.init(hexColor: "#cccccc"), forKeyPath: "_placeholderLabel.textColor")
    }
    
    
    // MARK:用户协议点击
    @objc func agreementTap(){
        let ctrl = UserAgreementViewController()
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    
    // MARK: 获取验证码
    @IBAction func getVerifiCode(_ sender: UIButton) {
        if self.phoneField.text?.count != 11  {
            PKhud.showText(text: "请输入正确的手机号~")
            self.phoneField.becomeFirstResponder()
            return
        }
        
        HttpRequest.requestData(.post, URLString: Api.get_code.rawValue, parameters: ["username":self.phoneField.text!,"type":0]) { (result) in
            if result["msg"] as! String == "success"{
                self.dispatchTimer(timeInterval: 1, handler: { (count) in
                    self.verificationBtn.setTitle("剩余"+"‘\(count)s", for: .normal)
                    sender.isUserInteractionEnabled = false
                })
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    
    
    @objc func imageViewTap(tap:UITapGestureRecognizer){
        let imgV = tap.view as! UIImageView
        if imgV == self.shopImage {
            self.isShopImg = true
        }else{
            self.isShopImg = false
        }
        changePortrait()
    }
    
    @objc func valueChange(textField:UITextField){
        
        var maxLength = 0
        if textField == self.phoneField {
            maxLength = 11
        }else if textField == self.verificationCodeField{
            maxLength = 4
        }else if textField == passWordField || textField == confirmField{
            maxLength = 12
        }else if textField == self.shopNameField {
            maxLength = 30
        }else if textField == self.principalField {
            maxLength = 10
        }
        
        let toBeString = textField.text!
        let lang = textField.textInputMode?.primaryLanguage
        if lang == "zh-Hans" {
            let selectedRange = textField.markedTextRange
            if selectedRange == nil && toBeString.count > maxLength{
                let endIndex = toBeString.index(toBeString.startIndex, offsetBy: maxLength)
                textField.text = String(toBeString[..<endIndex])
            }
        }else if toBeString.count > maxLength {
            let endIndex = toBeString.index(toBeString.startIndex, offsetBy: maxLength)
            textField.text = String(toBeString[..<endIndex])
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    // MARK:勾选用户协议
    @IBAction func checkAgreementBtnClick(_ sender: UIButton) {
        self.checkImage.isHighlighted = !self.checkImage.isHighlighted
    }
    
    // MARK:注册
    @IBAction func registerBtnClick(_ sender: UIButton) {
        
        if self.phoneField.text?.count != 11  {
            PKhud.showText(text: "请输入正确的手机号~")
            self.phoneField.becomeFirstResponder()
            return
        }
        
        if self.verificationCodeField.text?.count != 4 {
            PKhud.showText(text: "请输入正确的验证码~")
            self.verificationCodeField.becomeFirstResponder()
            return
        }
        
        if (self.passWordField.text?.count)! < 6 {
            PKhud.showText(text: "密码强度过低，需至少6位~")
            self.passWordField.becomeFirstResponder()
            return
        }
        
        if self.passWordField.text != self.confirmField.text {
            PKhud.showText(text: "两次密码不一致，请重新填写~")
            self.confirmField.becomeFirstResponder()
            return
        }
        
        if self.shopNameField.text?.count == 0 {
            PKhud.showText(text: "必须填写门店信息~")
            return
        }
        
        if self.principalField.text?.count == 0 {
            PKhud.showText(text: "必须填写负责人信息~")
            return
        }
        
        if self.shopImgUrl == "" {
            PKhud.showText(text: "必须上传门店照片~")
            return
        }
        
        if self.checkImage.isHighlighted == false {
            PKhud.showText(text: "请同意用户注册协议~")
            return
        }
        
        self.registerMethod()
        
    }
    
    func registerMethod(){
        let parameter:postParameters = ["username":self.phoneField.text!,
                                        "code":self.verificationCodeField.text!,
                                        "storeName":self.shopNameField.text!,
                                        "name":self.principalField.text!,
                                        "address":self.detailAddressTextView.text!,
                                        "storeImg":self.shopImgUrl,
                                        "licenseImg":self.businessLicenseImgUrl,
                                        "areaId":self.areaId,
                                        "password":self.passWordField.text!,
                                        "cityId":self.cityId]
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.register.rawValue, parameters: parameter) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                self.alertView.showAlert()
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    
    func dispatchTimer(timeInterval: Double, handler:@escaping (Int)->()){
        var timeCount = 61
        let codeTimer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
        codeTimer.schedule(deadline: .now(), repeating: timeInterval)
        codeTimer.setEventHandler(handler: {
            
            timeCount = timeCount - 1
            
            if timeCount <= 0 {
                codeTimer.cancel()
            }
            
            DispatchQueue.main.async {
                if timeCount <= 0 {
                    self.verificationBtn.isUserInteractionEnabled = true
                    self.verificationBtn.setTitle("获取验证码", for: .normal)
                }else{
                    handler(timeCount)
                }
                
            }
        })
        codeTimer.resume()
    }
    
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 4
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        switch section {
        case 0,1:
            return 4
        case 2,3:
            return 1
        default:
            return 0
        }
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section != 0 {

            var headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "headerView")
            if headerView == nil {
                headerView = UITableViewHeaderFooterView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 43))
                let bgView = UIView.init(frame: (headerView?.bounds)!)
                bgView.backgroundColor = UIColor.backgroundColor
                headerView?.backgroundView = bgView
                
                self.leftTitleLabel = Utils.labelWith(frame: CGRect.init(x: 13, y: 0, width: UIScreen.ScreenWidth, height: 14), font: UIFont.boldSystemFont(ofSize: 14), textAlignment: .left, textColor: "000000", text: "门店信息")
                self.leftTitleLabel.centerY = (headerView?.centerY)!
                headerView?.addSubview(self.leftTitleLabel)
            }
            
            if section == 1 {
                self.leftTitleLabel.text = "门店信息"
            }else if section == 2{
                self.leftTitleLabel.text = "门店照片"
            }else {
                if section == 3 {
                    let attributedString = NSMutableAttributedString(string: "营业执照上传（选填）")
                    attributedString.addAttributes([NSAttributedStringKey.foregroundColor:UIColor(red: 0.0 / 255.0, green: 0.0 / 255.0, blue: 0.0 / 255.0, alpha: 1.0)], range: NSRange(location: 0, length: 6))
                    attributedString.addAttributes([NSAttributedStringKey.foregroundColor:UIColor(red: 51.0 / 255.0, green: 51.0 / 255.0, blue: 51.0 / 255.0, alpha: 1.0),NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14)], range: NSRange(location: 6, length: 4))
                    self.leftTitleLabel.attributedText = attributedString
                }
            }
            return headerView
        }
        return UIView()
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 0 ? 0.01 : 43
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 1 {
            if indexPath.row == 2 {
                // 选择地址
                self.showAddressPicker()
            }
        }
    }

    

}

extension RegisterTableViewController:UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {//TZImagePickerControllerDelegate
    
    func textViewDidChange(_ textView: UITextView) {
        let toBeString = textView.text!
        let lang = textView.textInputMode?.primaryLanguage
        if lang == "zh-Hans" {
            let selectedRange = textView.markedTextRange
            if selectedRange == nil && toBeString.count > 50{
                let endIndex = toBeString.index(toBeString.startIndex, offsetBy: 50)
                textView.text = String(toBeString[..<endIndex])
            }
        }else if toBeString.count > 50 {
            let endIndex = toBeString.index(toBeString.startIndex, offsetBy: 50)
            textView.text = String(toBeString[..<endIndex])
        }
        self.countLabel.text = "\(textView.text.count)" + "/50"
        
        self.placeHolderLabel.isHidden = textView.text.count == 0 ? false : true
    }
    
    
    // MARK: 选择相机，相册
    func changePortrait() {
        
        self.photo()
//        let alertController = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
//        // 1.判断相机是否可用，如果可用就有拍照选项，反正则没有。
//        // 判断相机是否可用
//        if UIImagePickerController.isSourceTypeAvailable(.camera) {
//            alertController.addAction(UIAlertAction.init(title: "相机", style: .default, handler: { (action) in
//                self.camera()
//            }))
//        }
//        alertController.addAction(UIAlertAction.init(title: "相册", style: .default, handler: { (action) in
//            self.photo()
//        }))
//        alertController.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: { (action) in
//        }))
//        self.present(alertController, animated: true, completion: nil)
    }
    
    // MARK: 调用照相机方法
    func camera(){
        let pick:UIImagePickerController = UIImagePickerController()
        pick.delegate = self
        pick.allowsEditing = true
        pick.sourceType = UIImagePickerControllerSourceType.camera
        self.present(pick, animated: true, completion: nil)
    }
    
    // MARK: 调用照片方法
    func photo(){
        self.hx_presentAlbumListViewController(with: self.manager, done: { (allList, photoList, videoList, imgArray, original, ctrl) in
            self.navigationController?.navigationBar.isTranslucent = false
            if self.isShopImg {
                self.shopImage.contentMode = .scaleAspectFill
                self.shopImage.image = imgArray!.first
                self.uploadImage(img: imgArray!.first!)
            }else{
                self.businessLicenseImage.contentMode = .scaleAspectFill
                self.businessLicenseImage.image = imgArray!.first
                self.uploadImage(img: imgArray!.first!)
            }
        }) { (ctrl) in
            self.navigationController?.navigationBar.isTranslucent = false
        }
    }
    
    // MARK: 选择图片成功后代理(上传图片)-网络
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    
        picker.dismiss(animated: true, completion:nil)
    }
    
    // MARK:显示地址选择器
    func showAddressPicker(){
        if self.cityArray.count == 0 {
            self.getProvinceList()
        }else{
            UIView.animate(withDuration: 0.3,animations: {
                self.effect.alpha = 1
            }){(_)in
                self.addressPickerView.top = UIScreen.ScreenHeight - (220 + (Utils.isIphoneX() ? 34 : 0))
            }
        }
        
    }
    
    func hidenAddressPicker(){
        UIView.animate(withDuration: 0.2, animations: {
            self.addressPickerView.top = UIScreen.ScreenHeight
        }) { (_) in
            self.effect.alpha = 0
        }
    }
    
    func getProvinceList(){
        HttpRequest.requestData(.post, URLString: Api.provinceList.rawValue) { (result) in
            if result["msg"] as! String == "success" {
                if let cityArray = ([ProvinceModel].deserialize(from: result["data"] as? [Any])) as? [ProvinceModel] {
                    self.cityArray = cityArray
                }
//                print(self.cityArray)
                UIView.animate(withDuration: 0.3,animations: {
                    self.effect.alpha = 1
                }){(_)in
                    self.addressPickerView.top = UIScreen.ScreenHeight - (220 + (Utils.isIphoneX() ? 34 : 0))
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
}

extension RegisterTableViewController:HXAlbumListViewControllerDelegate{
//    func albumListViewController(_ albumListViewController: HXAlbumListViewController!, didDoneAllImage imageList: [UIImage]!) {
//        if self.isShopImg {
//            self.shopImage.contentMode = .scaleAspectFill
//            self.shopImage.image = imageList.first
//            self.uploadImage(img: imageList.first!)
//        }else{
//            self.businessLicenseImage.contentMode = .scaleAspectFill
//            self.businessLicenseImage.image = imageList.first
//            self.uploadImage(img: imageList.first!)
//        }
//
//    }
    
    func uploadImage(img:UIImage){
        
        HttpRequest.uploadImage(image: img) { (result) in
            if result["msg"] as! String == "success"{
                if self.isShopImg {
                    self.shopImgUrl = result["data"] as! String
                }else{
                    self.businessLicenseImgUrl = result["data"] as! String
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
}

























